package com.lottery.im.view;

import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.support.v7.widget.AppCompatTextView;
import android.util.AttributeSet;
import android.view.animation.AccelerateDecelerateInterpolator;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 作者：cyy
 * 时间：2018/9/28。
 */
public class DancingView extends AppCompatTextView {
  public static final String PLACEHOLDER = "@@@";
  private int duration;
  private String format = "%.0f";
  private float factor;
  private ArrayList<Float> numbers;
  private float[] numberTemp;
  private String text;
  private String textPattern;

  public DancingView(Context context, AttributeSet attrs) {
    super(context, attrs);
    TypedArray ta =
        context.obtainStyledAttributes(attrs, me.trojx.dancingnumber.R.styleable.DancingNumberView);
    this.duration =
        ta.getInteger(me.trojx.dancingnumber.R.styleable.DancingNumberView_dnv_duration, 1500);
    this.format = ta.getString(me.trojx.dancingnumber.R.styleable.DancingNumberView_dnv_format);
  }

  public void dance() {
    this.text = this.getText().toString();
    this.numbers = new ArrayList();
    Pattern pattern = Pattern.compile("\\d+(\\.\\d+)?");
    Matcher matcher = pattern.matcher(this.text);

    while (matcher.find()) {
      this.numbers.add(Float.parseFloat(matcher.group()));
    }

    this.textPattern = this.text.replaceAll("\\d+(\\.\\d+)?", "@@@");
    this.numberTemp = new float[this.numbers.size()];
    ObjectAnimator objectAnimator =
        ObjectAnimator.ofFloat(this, "factor", new float[] { 0.0F, 1.0F });
    objectAnimator.setDuration((long) this.duration);
    objectAnimator.setInterpolator(new AccelerateDecelerateInterpolator());
    objectAnimator.start();
  }

  public float getFactor() {
    return this.factor;
  }

  public void setFactor(float factor) {
    String textNow = this.textPattern;
    this.factor = factor;

    for (int i = 0; i < this.numberTemp.length; ++i) {
      this.numberTemp[i] = (Float) this.numbers.get(i) * factor;
      textNow = textNow.replaceFirst("@@@", String.format(this.format, this.numberTemp[i]));
    }

    this.setText(textNow);
  }

  public int getDuration() {
    return this.duration;
  }

  public void setDuration(double nubmer) {
    if (nubmer <= 10) {
      duration = 1000;
    } else if (nubmer > 10 && nubmer <= 50) {
      duration = 1500;
    } else if (nubmer > 50 && nubmer <= 100) {
      duration = 2000;
    } else if (nubmer > 100 && nubmer <= 500) {
      duration = 2500;
    } else if (nubmer > 500 && nubmer <= 1000) {
      duration = 3000;
    } else if (duration > 1000 && nubmer <= 5000) {
      duration = 3500;
    } else {
      duration = 4000;
    }
    //this.duration = duration;
  }

  public String getFormat() {
    return this.format;
  }

  public void setFormat(String format) {
    this.format = format;
  }
}
